using Tycho.Parser.Tokens;

namespace Tycho.Parser.Peg {
    public class SequenceRule<Context> : Rule<Context> {
        public Rule<Context>[] Rules;

        public SequenceRule (params Rule<Context>[] rules) {
            Rules = rules;
        }

        protected override RuleParseResult<Context> ReallyParse (Token[] tokens, int index, Context context) {
            RuleParseResult<Context> lastResult = null;
            foreach (var element in Rules) {
                RuleParseResult<Context> result = element.Parse (tokens, index, context);

                if (result == null) {
                    return null;
                }

                if (lastResult != null) {
                    result.MergeCapturesFrom (lastResult);
                }

                lastResult = result;

                index = result.Index;
                context = result.Context;
            }

            return lastResult;
        }
    }
}